package org.kalai.unifypay.servlet;

import com.alibaba.fastjson.JSON;

import org.apache.log4j.Logger;
import org.kalai.unifypay.bean.Member;
import org.kalai.unifypay.bean.Transflow;
import org.kalai.unifypay.util.CommonUtil;
import org.kalai.unifypay.util.DataDao;
import org.kalai.unifypay.util.DateUtil;
import org.kalai.unifypay.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zealotpz on 16/9/9. 订单/商户信息查询接口
 */

@WebServlet(urlPatterns = "/OrderOrMerchantQuery")
public class OrderOrMerchantQuery extends HttpServlet {

    private static final long   serialVersionUID = 2747139250656675042L;

    private static final Logger logger           = Logger.getLogger(OrderOrMerchantQuery.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // CommonUtil.responseObject(resp, Constant.ERROR_REQEST);
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        Map<String, String> param = CommonUtil.validate(request, response);
        if (param != null) {// 验证通过 返回参数集合
            logger.info("接收到订单/商户信息查询请求：" + param);
            Object result = CommonUtil.createRespMap("10", "系统异常");
            try {
                String type = param.get("type"); // 查询类型
                String orderNo = param.get("orderNo"); // 外部订单号
                String memberNo = param.get("memberNo"); // 会员号
                String partnerCode=request.getParameter("partnerCode");//合作方编码
                if (StringUtil.isEmpty(type)) {
                    logger.error(String.format("查询类型错误：type=%s", type));
                    throw new RuntimeException("#200-业务参数错误");
                } else if ("1".equals(type)) {// 订单查询
                    if (StringUtil.isEmpty(orderNo)) { // 外部订单号
                        logger.error(String.format("查询参数错误：orderNo=%s", orderNo));
                        throw new RuntimeException("#200-业务参数错误");
                    }
                    // 获取流水
                    Transflow transflow = DataDao.getInstance().getTransflowByOrderNo(partnerCode,orderNo);
                    if (result == null) {
                        result = CommonUtil.createRespMap("214", "未查询到数据");
                    } else {
                        Map<String, Object> TransflowMap = new HashMap<>();
                        TransflowMap.put("tranxSN", transflow.getTranxSN());
                        TransflowMap.put("orderNo", transflow.getOrderNo());
                        TransflowMap.put("bizcode", transflow.getBizcode());
                        TransflowMap.put("memberNo", transflow.getMemberNo());
                        TransflowMap.put("transAmt", transflow.getTransAmt());
                        TransflowMap.put("transTime",DateUtil.format(transflow.getTransTime(),DateUtil.YYYYMMDDHHMMSS));
                        TransflowMap.put("payTime",transflow.getPayTime()==null?"":DateUtil.format(transflow.getPayTime(),DateUtil.YYYYMMDDHHMMSS));
                        TransflowMap.put("notifyUrl", transflow.getNotifyUrl());
                        TransflowMap.put("status", transflow.getStatus());
                        TransflowMap.put("respCode", "00");
                        TransflowMap.put("respDesc", "查询成功");
                        result = TransflowMap;
                    }
                    // logger.info("订单查询返回："+result);
                } else if ("2".equals(type)) {// 商户信息查询
                    if (StringUtil.isEmpty(memberNo)) { // 会员号
                        logger.error(String.format("查询参数错误：memberNo=%s", memberNo));
                        throw new RuntimeException("#200-业务参数错误");
                    }
                    // 获取会员信息
                    Member member = DataDao.getInstance().getMember(partnerCode,memberNo);
                    if(member==null)
                    {
                        result = CommonUtil.createRespMap("214", "未查询到数据");
                    }
                    else
                    {
                        // 获取会员业务信息
                        List<Map<String, Object>> memberBiz = DataDao.getInstance().getMerchantBiz(memberNo);
    
                        Map<String, Object> memberInfo = new HashMap<>();
                        memberInfo.put("partnerCode", member.getPartnerCode());
                        memberInfo.put("memberName", member.getMemberName());
                        memberInfo.put("memberCertno", member.getMemberCertno());
                        memberInfo.put("acctNo", member.getAcctNo());
                        memberInfo.put("bankNo", member.getBankNo());
                        memberInfo.put("bankName", member.getBankName());
                        memberInfo.put("bizList", memberBiz);
                        memberInfo.put("respCode", "00");
                        memberInfo.put("respDesc", "查询成功");
    
                        result = memberInfo;
                    }
                } else {
                    logger.error(String.format("查询参数错误-：type=%s", type));
                    throw new RuntimeException("#200-业务参数错误");
                }
            } catch (Exception e) {
                String message = e.getMessage();
                if (message != null && message.startsWith("#")) {
                    result = CommonUtil.createRespMap(message.substring(1, message.indexOf("-")),
                            message.substring(message.indexOf("-") + 1));
                } else {
                    result = CommonUtil.createRespMap("10", e.getMessage());
                    e.printStackTrace();
                }
            } finally {
                CommonUtil.responseObject(response, JSON.toJSONString(result));
            }

        }

    }

}
